package com.woniu.config;

import com.github.dockerjava.api.DockerClient;


import com.woniu.util.DockerClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.lang.Nullable;




public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;



    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer){
        super(listenerContainer);
    }

    public void onMessage(Message message, @Nullable byte[] pattern) {
        //1.连接docker容器
        DockerClient dockerClient = DockerClientUtils.connectDocker("tcp://192.168.232.121:2375");
        //3.拿到过期的key
        String key = message.toString();
        if (key.startsWith("container_")){
            String containerID = key.substring(key.lastIndexOf("_") + 1);
            DockerClientUtils.stopContainer(dockerClient,containerID);
            DockerClientUtils.removeContainer(dockerClient,containerID);
        }


        System.out.println("监听到key:" + key + "过期");

    }

}
